//生成ETH新钱包
package wallet

import (
	"crypto/ecdsa"
	"fmt"
	"log"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/crypto"
	"golang.org/x/crypto/sha3"
)

func GenerateWallet() {
	//生成随机私钥
	privateKey, err := crypto.GenerateKey()
	if err != nil {
		log.Fatal(err)
	}

	//1.将随机私钥转换为字节 2.字节转换为十六进制字符串 3.十六进制编码之后删除“0x” 4.最后输出用于签署交易的私钥
	privateKeyBytes := crypto.FromECDSA(privateKey)
	fmt.Println(hexutil.Encode(privateKeyBytes)[2:])

	//通过随机私钥生成公钥（公钥是从私钥派生的）
	publicKey := privateKey.Public()
	publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
	if !ok {
		log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
	}

	//将其转换为十六进制的过程与转化私钥的过程类似。剥离了0x和前2个字符04，它始终是EC前缀，不是必需的，最后输出公钥
	publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
	fmt.Println(hexutil.Encode(publicKeyBytes)[4:])

	address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
	fmt.Println(address) // 0x0973eF8A94B8f11FaD4BDD076FFeAd2c27Fa73CE

	hash := sha3.NewLegacyKeccak256()
	hash.Write(publicKeyBytes[1:])
	fmt.Println(hexutil.Encode(hash.Sum(nil)[12:])) //输出我们经常看到的ETH地址：0x0973ef8a94b8f11fad4bdd076ffead2c27fa73ce

}

